<template>
    <div class="content">
        <!-- :style="{ width: singleSetVisible ? 'calc(100% - 600px)' : '100%' }" -->
        <div class="left-content">
            <el-form class="form">
                <el-form-item label="产品代码/名称">
                    <!-- <RiskEntryInputs
                        @set-entry-data="val => (searchParams.fundProductCodes = val)"
                        :showDis="false"
                        :showAll="false"
                        :returnDatas="searchParams.fundProductCodes"
                        dictKey="fundProductCode"
                      
                    /> -->
                    <el-select v-model="searchParams.fundProductCodes" filterable multiple collapse-tags clearable size="mini" class="item">
                        <el-option
                            v-for="i in computedFundStorage"
                            :key="i.fundProductCode"
                            :label="i.fundProductCode + ' ' + i.fundName"
                            :value="i.fundProductCode"
                        >
                        </el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="条目说明">
                    <el-input v-model="searchParams.entryName" size="mini" class="item" clearable></el-input>
                </el-form-item>
                <el-form-item label-width="0px">
                    <el-button size="mini" type="primary" @click="handleBtn('search')">查询</el-button>
                    <el-button size="mini" @click="handleBtn('batchSet')">批量设置</el-button>
                    <el-button size="mini" @click="handleBtn('sponsorSet')">主办设置</el-button>
                    <!-- <el-button size="mini" type="primary" @click="handleBtn('loadout')">导出</el-button> -->
                </el-form-item>
            </el-form>
            <RiskTableP
                ref="risk-table"
                :tableConfig="tableConfig"
                :tableData="tableData"
                :column="tableColumns"
                :paging="paging"
                v-loading="tableLoading"
                @page-change="getTableData"
                style="height: calc(100% - 60px)"
            >
                <template #operation="{ row }">
                    <RiskIconButton type="primary" icon="el-icon-edit" @on-click="handleBtn('update', row)" topTitle="修改" />
                </template>
            </RiskTableP>
        </div>
        <!-- 批量 -->
        <yh-dialog :visible.sync="batchSetVisible" v-if="batchSetVisible" title="批量参数设置" width="630px" :close-on-click-modal="false" drag>
            <BatchSetContent ref="batchSetRef" :infoGroupOptions="infoGroupOptions"></BatchSetContent>
            <div slot="footer" class="dialog-footer">
                <el-button size="mini" @click="handleDialogBtn('batch-cancel')">取 消</el-button>
                <el-button size="mini" type="primary" @click="handleDialogBtn('batch-confirm')" v-loading="setUploading">确 定</el-button>
            </div>
        </yh-dialog>
        <!-- 单个 -->
        <el-drawer
            title="参数设置修改"
            :with-header="false"
            :before-close="handleClose"
            :visible.sync="singleSetVisible"
            direction="rtl"
            custom-class="demo-drawer"
            ref="drawer"
            :close-on-press-escape="false"
            :wrapperClosable="false"
            size="600px"
        >
            <BatchSetContent ref="singleSetRef" :infoGroupOptions="infoGroupOptions" :overrunInfo="currentOverrunInfo"></BatchSetContent>
            <div class="demo-drawer__footer">
                <el-button @click="handleDialogBtn('single-cancel')">取 消</el-button>
                <el-button type="primary" @click="handleDialogBtn('single-confirm')" :loading="loading">{{
                    loading ? '提交中 ...' : '确 定'
                }}</el-button>
            </div>
        </el-drawer>
        <yh-dialog
            drag
            title="配置分发维护"
            :visible.sync="sponsorSetVisible"
            :close-on-click-modal="false"
            :close-on-press-escape="false"
            width="700px"
        >
            <el-form label-width="110px" ref="configParam">
                <div v-for="(item, index) in configParamList" :key="index" class="form-config">
                    <el-form-item :label="'产品类型' + (index + 1) + ':'" prop="fundType">
                        <el-select v-model="item.fundType" size="mini" disabled>
                            <el-option v-for="(value, key) in fundTypeOptions" :key="key" :value="key" :label="value"></el-option>
                        </el-select>
                    </el-form-item>
                    <el-form-item label="主办人:" :prop="leaderCode">
                        <!-- <RiskEntryInputPlus
                            class="my-select"
                            :requestParams="{
                                url: '/outFrame/userInfo/list/like?userCodeAndName=',
                                method: 'get',
                            }"
                            :info="{
                                key: 'userCode',
                                name: 'userNickName',
                            }"
                            @set-entry-data="value => (item.leaderCode = value)"
                            :returnDatas="item.leaderCode"
                        /> -->
                        <el-select v-model="item.leaderCode" size="mini" class="item" clearable filterable>
                            <el-option v-for="item in userOptions" :key="item.userCode" :value="item.userCode" :label="item.userName"></el-option>
                        </el-select>
                    </el-form-item>
                </div>
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button @click="sponsorSetVisible = false"> 取 消 </el-button>
                <el-button type="primary" @click="sponsorSetSubmit" v-loading="sponsorLoading"> 确 认 </el-button>
            </div>
        </yh-dialog>
    </div>
</template>
<script lang="ts">
import RiskTableP from '@/common/components/risk-table-plus.vue';
import { Component, Vue } from 'vue-property-decorator';
import { PageVO, TableConfigVO } from '@/common/vo';
import BatchSetContent from './batch-set-content.vue';
import API from '../api/process-handling';
import RiskIconButton from '@/common/components/risk-icon-button.vue';
import RiskEntryInputPlus from '@/common/components/risk-entry-input-plus.vue';
import RiskEntryInputs from '@/common/components/risk-entry-inputs.vue';
import { SGU_CACHE } from '@/utils/diction-const-util';
import { changeOptions } from '@/utils/tools';
@Component({ name: 'RiskSetup', components: { RiskTableP, BatchSetContent, RiskIconButton, RiskEntryInputPlus, RiskEntryInputs } })
export default class RiskSetup extends Vue {
    currentOverrunInfo: any = {};
    batchSetVisible: boolean = false;
    singleSetVisible: boolean = false;
    sponsorSetVisible: boolean = false;
    sponsorLoading: boolean = false;
    setUploading: boolean = false; // 设置loading
    userOptions: any[] = []; // 主办人下拉框值
    searchParams: any = {
        fundProductCodes: [],
        entryName: '',
    };
    paging: PageVO = {
        currentPage: 1,
        pageSize: 25,
        total: 0,
    };
    tableLoading: boolean = false;
    tableConfig: TableConfigVO = {
        rowKey: 'overrunSetId', // 主键key
        allRowKeys: [], // 所有页数据的key集合
    };
    tableData: any[] = [];
    tableColumns = [
        {
            type: 'checkbox',
            selectedAll: false,
            fixed: 'left',
            align: 'center',
            width: 60,
        },
        {
            title: '条目编号',
            field: 'entryCode',
            width: '100px',
        },
        {
            title: '条目说明',
            field: 'entryName',
        },
        {
            title: '是否偏严',
            field: 'sirict',
            render: value => this.yOrNPojo[value],
        },
        {
            title: '自动发送',
            field: 'autoApprove',
            render: value => this.yOrNPojo[value],
        },
        {
            title: '自动关闭',
            field: 'autoClose',
            render: value => this.yOrNPojo[value],
        },
        {
            title: '操作',
            field: 'operation',
            width: 80,
            align: 'center',
        },
    ];

    yOrNPojo = {
        '0': '否',
        '1': '是',
    };
    // 分发配置参数
    configParamList = [
        // {
        //     fundType: 'A',
        //     leaderCode: '',
        // },
        // {
        //     fundType: 'B',
        //     leaderCode: '',
        // },
        // {
        //     fundType: 'C',
        //     leaderCode: '',
        // },
        // {
        //     fundType: 'D',
        //     leaderCode: '',
        // },
    ];

    fundTypeOptions: any = {
        A: '集合',
        B: '单一',
        C: '专项',
        D: '公募',
    };
    infoGroupOptions: any = [];

    fundStorage: any[] = [];
    // 已选项前置
    get computedFundStorage() {
        let arr = changeOptions(this.searchParams.fundProductCodes, this.fundStorage, 'fundProductCode');
        return arr;
    }
    async mounted() {
        this.fundStorage = await SGU_CACHE('FundInfoByUser', '/fundInfo/list/byUser/like', []);

        this.getTableData();
        this.getUserOptionsList();
        this.getAllGroupList();
    }

    /**
     * 所有通知组数据
     */
    getAllGroupList() {
        API.getAllInfoGroupList()
            .then((res: any) => {
                this.infoGroupOptions =
                    res.map(item => {
                        return {
                            userGroupNoticeCode: String(item.userGroupNoticeCode),
                            noticeName: item.noticeName,
                        };
                    }) || [];
            })
            .catch(() => {
                // const res = [
                //     { userGroupNoticeCode: 123, noticeName: '投资经理组' },
                //     { userGroupNoticeCode: 234, noticeName: 'zhanbgpei' },
                // ];
                // this.infoGroupOptions =
                //     res.map(item => {
                //         return {
                //             userGroupNoticeCode: String(item.userGroupNoticeCode),
                //             noticeName: item.noticeName,
                //         };
                //     }) || [];
            });
    }

    /**
     * 主办人下拉值
     */
    getUserOptionsList() {
        API.getUserList()
            .then((res: any) => {
                this.userOptions = res;
            })
            .catch(err => {
                this.userOptions = [
                    {
                        userCode: '1234',
                        userName: 'xz',
                    },
                    {
                        userCode: '8765',
                        userName: 'xl',
                    },
                    {
                        userCode: '1209',
                        userName: 'xt',
                    },
                ];
                console.log(err, 'getUserList');
            });
    }

    /**
     * 表格数据
     */
    getTableData(type?: string) {
        this.tableLoading = true;
        API.handleConfigList({ ...this.searchParams, paging: this.paging })
            .then((res: any) => {
                this.tableData = res?.list || [];
                this.paging.total = res?.total || 0;
            })
            .catch(() => {})
            .finally(() => {
                this.tableLoading = false;
                // this.tableData = [
                //     {
                //         overrunSetId: '1221',
                //         entryCode: '123',
                //         sirict: '0',
                //         autoApprove: '1',
                //         autoClose: '1',
                //         flowSettingPOList: [
                //             {
                //                 overrunType: '0',
                //                 overrunValue: '1',
                //                 userGroupNoticeCodes: ['123'],
                //             },
                //             {
                //                 overrunType: '1',
                //                 overrunValue: '80',
                //                 userGroupNoticeCodes: ['123'],
                //             },
                //             {
                //                 overrunType: '2',
                //                 overrunValue: '2',
                //                 userGroupNoticeCodes: ['234'],
                //             },
                //         ],
                //     },
                // ];
            });
    }

    /**
     * 按钮点击
     */
    async handleBtn(type: string, row?: any) {
        if (type == 'search') {
            this.paging.currentPage = 1;
            this.getTableData('search');
        } else if (type == 'batchSet') {
            const checkedKeys = (this.$refs['risk-table'] as any).checkRowKeys;
            if (checkedKeys.length < 1) {
                this.yh_message_info('请先勾选需批量设置的数据');
                return;
            }
            this.batchSetVisible = true;
            // this.$nextTick(() => {
            //     const $ref = this.$refs['batchSetRef'] as any;
            //     $ref.resetParams();
            // });
        } else if (type == 'sponsorSet') {
            // this.$nextTick(() => {
            //     const $ref = this.$refs['configParam'] as any;
            //     $ref.resetFields();
            // });
            // 获取主办设置信息
            API.queryHostSetting()
                .then((res: any) => {
                    this.configParamList = res;
                    this.sponsorSetVisible = true;
                })
                .catch(() => {});
        } else if (type == 'update') {
            this.singleSetVisible = true;
            // 给定单行的值或者调用接口获取详情or指定行数据
            API.singleSettingDetail({ overrunSetId: row.overrunSetId })
                .then((res: any) => {
                    this.currentOverrunInfo = res;
                })
                .catch(() => {
                    //     this.currentOverrunInfo = {
                    //         overrunSetId: '1221',
                    //         entryCode: '123',
                    //         sirict: '0',
                    //         autoApprove: '1',
                    //         autoClose: '1',
                    //         flowSettingPOList: [
                    //             {
                    //                 overrunType: '0',
                    //                 overrunValue: '1',
                    //                 userGroupNoticeCodes: ['123'],
                    //             },
                    //             {
                    //                 overrunType: '1',
                    //                 overrunValue: '80',
                    //                 userGroupNoticeCodes: ['123'],
                    //             },
                    //             {
                    //                 overrunType: '2',
                    //                 overrunValue: '2',
                    //                 userGroupNoticeCodes: ['234'],
                    //             },
                    //         ],
                    //     };
                });
        }
        // else if (type == 'loadout') {
        //     const checkedKeys = (this.$refs['risk-table'] as any).checkRowKeys;
        //     const data = checkedKeys.length ? { checkedKeys } : this.searchParams;
        //     API.downLoadFileConfig(data);
        //     // 清除导出时列表勾选项
        //     this.$nextTick(() => {
        //         (this.$refs['risk-table'] as any).resetCheckRowKeys();
        //     });
        // }
    }

    /**
     * 主办设置"确认"
     */
    sponsorSetSubmit() {
        for (let item of this.configParamList) {
            if (!item['leaderCode']) {
                this.yh_message_info('主办人信息不可为空！');
                return;
            }
        }

        return new Promise((resolve, reject) => {
            this.sponsorLoading = true;
            API.sponsorSet({ fundLeaderPOList: this.configParamList })
                .then(res => {
                    this.sponsorSetVisible = false;
                    this.yh_message_success('主办设置成功！');
                    resolve(res);
                })
                .catch(err => {
                    reject(err);
                })
                .finally(() => {
                    this.sponsorLoading = false;
                });
        });
    }

    /**
     * 弹框按钮
     */
    handleDialogBtn(type: string) {
        if (type == 'batch-confirm' || type == 'single-confirm') {
            let checkedKeys = [];
            let refName = 'batchSetRef';
            let requestName = API.batchSet;
            if (type == 'single-confirm') {
                refName = 'singleSetRef';
                requestName = API.handleConfigUpdate;
                checkedKeys = [this.currentOverrunInfo.overrunSetId];
            } else {
                checkedKeys = (this.$refs['risk-table'] as any).checkRowKeys;
            }
            const $ref = this.$refs[refName] as any;

            const { setInfo, transfiniteTypes } = $ref;
            console.log(setInfo, transfiniteTypes, 'info');
            for (let index in transfiniteTypes) {
                console.log(typeof index, 'index');
                const item = transfiniteTypes[index];
                if (!item.overrunType || (!item.overrunValue && item.overrunValue !== 0) || !item.userGroupNoticeCodes?.length) {
                    this.yh_message_error(`第${Number(index) + 1}行配置项不完整`);
                    return;
                }
            }
            this.setUploading = true;
            return new Promise((resolve, reject) => {
                requestName({
                    ...setInfo,
                    flowSettingPOList: transfiniteTypes.map(item => {
                        item.overrunSetId = this.currentOverrunInfo.overrunSetId;
                        return item;
                    }),
                    overrunSetIdList: checkedKeys,
                })
                    .then(res => {
                        type == 'batch-confirm' && (this.batchSetVisible = false);
                        type == 'single-confirm' && (this.singleSetVisible = false);
                        this.getTableData();
                        $ref.resetParams();
                        const message = type == 'batch-confirm' ? '批量参数设置' : '参数设置修改';
                        this.yh_message_success(message + '成功');
                        this.$nextTick(() => {
                            (this.$refs['risk-table'] as any).resetCheckRowKeys();
                        });
                        resolve(res);
                    })
                    .catch(err => {
                        reject(err);
                    })
                    .finally(() => {
                        this.setUploading = false;
                    });
            });
        } else if (type == 'batch-cancel') {
            this.batchSetVisible = false;
        } else if (type == 'single-cancel') {
            this.singleSetVisible = false;
        }
    }
}
</script>
<style lang="scss" scoped>
.content {
    height: 100%;
    .left-content {
        height: 100%;
        width: 100%;
    }
    .form {
        display: grid;
        grid-template-columns: 1.5fr 1fr 4fr;
        border: 1px solid #ccc;
        padding: 8px;
        margin-bottom: 10px;
        .el-form-item {
            margin-bottom: 0px;
        }
        .item {
            width: 60%;
        }

        /deep/ .el-select__tags {
            flex-wrap: nowrap;

            .el-tag.el-tag--info {
                display: flex;
                align-items: center;

                .el-select__tags-text {
                    display: block;
                    font-size: 12px;
                    max-width: 80px;
                    white-space: nowrap;
                    overflow: hidden;
                    text-overflow: ellipsis;
                }
            }
        }
    }
}

.form-config {
    display: grid;
    grid-template-columns: repeat(2, 1fr);
    .el-form-item {
        margin-bottom: 10px;
    }
    .item {
        width: 100%;
    }
}

.demo-drawer__footer {
    text-align: end;
}
/deep/ .el-drawer__body {
    padding: 10px;
    display: flex;
    flex-direction: column;
    align-items: end;
    justify-content: space-between;
}
</style>
<style>
/* .demo-drawer {
    padding: 10px;
    display: flex;
    flex-direction: column;
    align-items: end;
    justify-content: space-between;
} */
</style>
